package com.cmes.core.utils;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;

/**
 * 异步工具类
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
public class AsyncUtils {

    public static final Executor COMMON_EXECUTOR;

    static {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); // 核心线程数
        executor.setMaxPoolSize(10); // 最大线程数
        executor.setQueueCapacity(200); // 队列大小
        executor.setThreadNamePrefix("common-"); // 线程前缀名
        executor.initialize();
        COMMON_EXECUTOR = executor;
    }

    public static CompletableFuture<Void> run(Runnable supplier) {
        return CompletableFuture.runAsync(supplier, COMMON_EXECUTOR);
    }

    public static CompletableFuture<Void> run(Runnable supplier, Executor executor) {
        return CompletableFuture.runAsync(supplier, executor);
    }

    public static <T> CompletableFuture<T> supply(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier, COMMON_EXECUTOR);
    }

    public static <T> CompletableFuture<T> supply(Supplier<T> supplier, Executor executor) {
        return CompletableFuture.supplyAsync(supplier, executor);
    }

}
